package com.yjj.im.Utils;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.os.Message;
import android.util.Log;

import com.yjj.im.bean.DataBean;
import com.yjj.im.ui.MessageActivity;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Random;
import java.util.concurrent.ScheduledExecutorService;

public class BlutetoothPrinterUtils {
    private Random random = new Random();
    private static final String TAG = "BlutetoothPrinter";

    private final int MSG_TEST                               = 1;
    private final int MSG_IS_NORMAL                          = 2;
    private BluetoothAdapter mBluetoothAdapter = null;
    private BluetoothDevice mBluetoothPrinterDevice = null;
    private BluetoothSocket socket = null;

    public final static String  PRINTER_NORMAL_ACTION = "com.iposprinter.iposprinterservice.NORMAL_ACTION";
    public final static String  GET_CUST_PRINTAPP_PACKAGENAME_ACTION = "android.print.action.CUST_PRINTAPP_PACKAGENAME";
    /*循环打印类型*/
    private final int  MULTI_THREAD_LOOP_PRINT  = 1;
    private final int  DEFAULT_LOOP_PRINT       = 0;

    /*定义打印机状态*/
    public final int PRINTER_NORMAL = 0;
    public final int PRINTER_ERROR_UNKNOWN = 5;
    /*打印机当前状态*/
    private int printerStatus = PRINTER_ERROR_UNKNOWN;
    //循环打印标志位
    private       int  loopPrintFlag            = DEFAULT_LOOP_PRINT;

    private boolean isBluetoothOpen = false;
    private static HandlerUtils.PrinterHandler mPrinterHandler;

    public static void setPriterHadler(HandlerUtils.PrinterHandler printerHandler){
        mPrinterHandler = printerHandler;
    }

    public BroadcastReceiver IPosPrinterStatusListener = new BroadcastReceiver(){
        @Override
        public void onReceive(Context context, Intent intent){
            String action = intent.getAction();
            if(action == null)
            {
                Log.d(TAG,"IPosPrinterStatusListener onReceive action = null");
                return;
            }
            // Log.d(TAG,"IPosPrinterStatusListener action = "+action);
            if(action.equals(PRINTER_NORMAL_ACTION))
            {
                mPrinterHandler.sendEmptyMessageDelayed(MSG_IS_NORMAL,0);
            }
            else if(action.equals(BluetoothAdapter.ACTION_STATE_CHANGED))
            {
                int state= intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,BluetoothAdapter.ERROR);
                switch (state) {
                    case BluetoothAdapter.STATE_OFF:
                        Log.d("aaa", "STATE_OFF 蓝牙关闭");
                        isBluetoothOpen = false;
                        break;
                    case BluetoothAdapter.STATE_TURNING_OFF:
                        Log.d("aaa", "STATE_TURNING_OFF 蓝牙正在关闭");
                        isBluetoothOpen = false;
                        if(mBluetoothAdapter != null)
                            mBluetoothAdapter = null;
                        if(mBluetoothPrinterDevice != null)
                            mBluetoothPrinterDevice = null;
                        try {
                            if (socket != null && (socket.isConnected())) {
                                socket.close();
                                socket = null;
                            }
                        }
                        catch (IOException e)
                        {
                            e.printStackTrace();
                        }
                        break;
                    case BluetoothAdapter.STATE_ON:
                        Log.d("aaa", "STATE_ON 蓝牙开启");
                        loopPrintFlag = DEFAULT_LOOP_PRINT;
                        isBluetoothOpen = true;
                        LoadBluetoothPrinter();
                        break;
                    case BluetoothAdapter.STATE_TURNING_ON:
                        isBluetoothOpen = true;
                        Log.d("aaa", "STATE_TURNING_ON 蓝牙正在开启");
                        break;
                }
            }
            else if(action.equals(GET_CUST_PRINTAPP_PACKAGENAME_ACTION))
            {
                String mPackageName = intent.getPackage();
                Log.d(TAG,"====GET_CUST_PRINTAPP_PACKAGENAME_ACTION："+action+"=======mPackageName:"+mPackageName);
            }
            else
            {
                mPrinterHandler.sendEmptyMessageDelayed(MSG_TEST,0);
            }
        }
    };

    public void LoadBluetoothPrinter()
    {
        // 1: Get BluetoothAdapter
        mBluetoothAdapter = BluetoothUtil.getBluetoothAdapter();
        if(mBluetoothAdapter == null)
        {
            //Toast.makeText(getBaseContext(), R.string.get_BluetoothAdapter_fail, Toast.LENGTH_LONG).show();
            isBluetoothOpen = false;
            return;
        }
        else
        {
            isBluetoothOpen =true;
        }
        //2: Get bluetoothPrinter Devices
        mBluetoothPrinterDevice = BluetoothUtil.getIposPrinterDevice(mBluetoothAdapter);
        if(mBluetoothPrinterDevice == null)
        {
            //Toast.makeText(getBaseContext(), R.string.get_BluetoothPrinterDevice_fail, Toast.LENGTH_LONG).show();
            return;
        }
        //3: Get conect Socket
        try {
            socket = BluetoothUtil.getSocket(mBluetoothPrinterDevice);
        }
        catch (IOException e)
        {
            e.printStackTrace();
            return;
        }
        //Toast.makeText(getBaseContext(), R.string.get_BluetoothPrinterDevice_success, Toast.LENGTH_LONG).show();
    }

    public int getPrinterStatus()
    {
        byte[] statusData = new byte[3];
        if(!isBluetoothOpen)
        {
            printerStatus = PRINTER_ERROR_UNKNOWN;
            return printerStatus;
        }
        if((socket == null) || (!socket.isConnected()))
        {
            try {
                socket = BluetoothUtil.getSocket(mBluetoothPrinterDevice);
            }
            catch (IOException e)
            {
                e.printStackTrace();
                return printerStatus;
            }
        }
        try {
            InputStream in = socket.getInputStream();
            OutputStream out = socket.getOutputStream();
            byte[] data = ESCUtil.getPrinterStatus();
            out.write(data,0,data.length);
            int readsize = in.read(statusData);
            //Log.e(TAG,"~~~ readsize:"+readsize+" statusData:"+statusData[0]+" "+statusData[1]+" "+statusData[2]);
            if((readsize > 0) &&(statusData[0] == ESCUtil.ACK && statusData[1] == 0x11)) {
                printerStatus = statusData[2];
            }
            out.close();
            in.close();
            socket.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }

        return printerStatus;
    }


    private void bluetoothPrinterTest(ArrayList<DataBean> list)
    {
        DataBean dataBean = list.get(0);

        ThreadPoolManager.getInstance().executeTask(new Runnable() {
            @Override
            public void run() {
                try{
                    byte[] printer_init = ESCUtil.init_printer();
                    byte[] fontSize0 = ESCUtil.fontSizeSet((byte) 0x00);
                    byte[] fontSize1 = ESCUtil.fontSizeSet((byte) 0x01);
                    byte[] fontSize2 = ESCUtil.fontSizeSet((byte) 0x10);
                    byte[] fontSize3 = ESCUtil.fontSizeSet((byte) 0x11);
                    byte[] lineH0 = ESCUtil.setLineHeight((byte)26);
                    byte[] lineH1 = ESCUtil.setLineHeight((byte)50);

                    byte[] align0 = ESCUtil.alignMode((byte)0);
                    byte[] align1 = ESCUtil.alignMode((byte)1);
                    byte[] align2 = ESCUtil.alignMode((byte)2);
                    byte[] title1 = "称重结果\n".getBytes("GBK");
                    String companys = MessageActivity.compayKeyList.get(dataBean.company);
                    String company1s = MessageActivity.compayKeyList.get(dataBean.company2);
                    String products = MessageActivity.compayKeyList.get(dataBean.product);
                    byte[] title2 = "\n".getBytes("GBK"); //
                    byte[] sign1 = "********************************\n".getBytes("GBK");
                    String company = "收货单位："+companys+"\n";
                    byte[] fontTest0 = company.getBytes("GBK");
                    String company1 = "发货单位："+company1s+"\n";
                    byte[] fontTest1 = company1.getBytes("GBK");
                    String product = "货名："+products+"\n";
                    byte[] fontTest2 = product.getBytes("GBK");
                    String weight = "净重："+dataBean.weight1+"\n";
                    byte[] fontTest3 = weight.getBytes("GBK");
                    String car = "车牌："+dataBean.car+"\n";
                    byte[] orderSerinum = car.getBytes("GBK");
                    String note = "备注："+dataBean.note+"\n";
                    byte[] specialSign= note.getBytes("GBK");
                    String bianhao = "编号："+dataBean.cserial+"\n";
                    byte[] testSign2 = bianhao.getBytes("GBK");
                    String time = "时间："+dataBean.ctime+"\n";
                    byte[] testInfo = time.getBytes("GBK");
                    byte[] testSign = "--------------------------------\n".getBytes("GBK");
                    byte[] nextLine = ESCUtil.nextLines(1);
                    byte[] performPrint = ESCUtil.performPrintAndFeedPaper((byte)200);

                    byte[][] cmdBytes = {printer_init,lineH0,fontSize3,align1,title1,fontSize1,title2,nextLine,align0,
                            fontSize0,sign1,fontSize0,fontTest0,lineH1,fontSize1,fontTest1,lineH0,fontSize2,fontTest2,
                            lineH1,fontSize3,fontTest3,align2,lineH0,fontSize0,orderSerinum,specialSign,testSign,
                            align1,fontSize1,lineH1,testInfo,nextLine,performPrint};
                    try {
//                        if(mBluetoothPrinterDevice == null){
//                            return;
//                        }
                        if((socket == null) || (!socket.isConnected()))
                        {
                            socket = BluetoothUtil.getSocket(mBluetoothPrinterDevice);
                        }
                        byte[] data = ESCUtil.byteMerger(cmdBytes);
                        OutputStream out = socket.getOutputStream();
                        out.write(data,0,data.length);
                        out.close();
                        socket.close();
                    }
                    catch (IOException e)
                    {
                        e.printStackTrace();
                    }
                }
                catch (UnsupportedEncodingException e)
                {
                    e.printStackTrace();
                }

            }
        });
    }
    /**
     * 消息处理
     */
    public HandlerUtils.IHandlerIntent mHandlerIntent = new HandlerUtils.IHandlerIntent()
    {
        @Override
        public void handlerIntent(Message msg)
        {
            Log.d(TAG,"-----------msg.what:"+msg.what);
            switch (msg.what)
            {
                case MSG_TEST:
                    break;
                case MSG_IS_NORMAL:
                    if (getPrinterStatus() == PRINTER_NORMAL) {
                        print_loop(loopPrintFlag);
                    }
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * 循环打印
     */
    public void print_loop(int flag)
    {
        switch (flag)
        {
            case MULTI_THREAD_LOOP_PRINT:
                multiThreadPrintTest();
                break;
            default:
                break;
        }
    }

    public void multiThreadPrintTest()
    {
        switch (random.nextInt(16))
        {
            case 0:
//                bluetoothPrinterTest(list);
                break;

            default:
                break;
        }
    }
    public void printBitmapTest(Bitmap bitmap)
    {
        ThreadPoolManager.getInstance().executeTask(new Runnable() {
            @Override
            public void run() {
//                Bitmap mBitmap1 = BitmapFactory.decodeResource(getResources(), R.mipmap.test_p);
//                Bitmap mBitmap2 = BitmapFactory.decodeResource(getResources(), R.mipmap.test);

                byte[] printer_init = ESCUtil.init_printer();
                byte[] selectChinese = ESCUtil.selectChineseMode();
                byte[] charCode = ESCUtil.selectCharCodeSystem((byte) 0x01);
                byte[] align0 = ESCUtil.alignMode((byte) 0);
                byte[] align1 = ESCUtil.alignMode((byte) 1);
                byte[] align2 = ESCUtil.alignMode((byte) 2);
                byte[] leftMargin0 = ESCUtil.printLeftMargin(0);
                byte[] nexLine = ESCUtil.nextLines(1);
                byte[] performPrint = ESCUtil.performPrintAndFeedPaper((byte) 160);

                byte[][] cmdBytes = {printer_init, selectChinese, charCode,leftMargin0,
//                        align0, BitMapUtil.getBitmapPrintData(bitmap,128,0),
//                        align1, BitMapUtil.getBitmapPrintData(bitmap,320,1),
                        align1,BitMapUtil.getBitmapPrintData(bitmap,384,1),
                };
//                byte[][] cmdBytes1 ={leftMargin0,
//                        align0, BitMapUtil.getBitmapPrintData(mBitmap1,128,0),
//                        align1, BitMapUtil.getBitmapPrintData(mBitmap1,256,0),
//                        align2,  BitMapUtil.getBitmapPrintData(mBitmap1,320,1),
//                        performPrint
//                };
                try {
                    if((socket == null) || (!socket.isConnected()))
                    {
                        socket = BluetoothUtil.getSocket(mBluetoothPrinterDevice);
                    }
                    byte[] data = ESCUtil.byteMerger(cmdBytes);
                    OutputStream out = socket.getOutputStream();
                    out.write(data, 0, data.length);
//                    byte[] data1 = ESCUtil.byteMerger(cmdBytes1);
//                    out.write(data1, 0, data1.length);
                    out.close();
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }


}
